﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Configuration;
using System.Web.Security;
using System.Collections;

public partial class ChangePassword : System.Web.UI.Page
{
    string NewPasswd = "";
    string OldPasswd = "";
    int id = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["gid"] == null)
        {
            Response.Redirect("../Login.aspx");
        }
        ErrorReport.Visible = false;
        if(!IsPostBack)
        {
                    SetTop(0);
        }
        DBaccess db = new DBaccess();
        DataSet ds = new DataSet();
        String sid = Session["mid"].ToString();
        ds = db.GetDataSet("select * from mr_v_comment where time > (select last_comment_time from mr_member where mid ='" + sid + "')");
        HyperLinkRecentComment.Text = "最新评论(" + ds.Tables[0].Rows.Count.ToString() + ")";
        HyperLinkRecentComment.NavigateUrl = "~/recentcomment.aspx";
        HyperLinkRecentComment.ForeColor = Color.Blue;
        ds = db.GetDataSet("select * from mr_v_download where time > (select last_download_time from mr_member where mid ='" + sid + "')");
        HyperLinkRecentDownload.Text = "最新下载(" + ds.Tables[0].Rows.Count.ToString() + ")";
        HyperLinkRecentDownload.NavigateUrl = "~/recentdownload.aspx";
        HyperLinkRecentDownload.ForeColor = Color.Blue;
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridViewDataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        OldPasswd = OldPassword.Text;
        DBaccess db = new DBaccess();
        SqlDataReader read = db.GetReader("select password from mr_member where mid='" + Session["mid"].ToString() + "'");
        read.Read();
        if (OldPasswd == read.GetValue(0).ToString())
        {
            ErrorReport.Text = "";
            if ((RegConfirm(NewPassword.Text) == 1) && (RegConfirm(PasswordConfirm.Text) == 1))
            {
                if (NewPassword.Text == PasswordConfirm.Text)
                {
                    NewPasswd = NewPassword.Text;
                    if (NewPasswd.Length > 20)
                    {
                        ErrorReport.Visible = true;
                        ErrorReport.BorderWidth = 1;
                        ErrorReport.BackColor = Color.FromArgb(255, 174, 201);
                        ErrorReport.ForeColor = Color.Red;
                        ErrorReport.Text = "您输入的新密码过长，请检查后正确输入！";
                        NewPassword.Text = "";
                        PasswordConfirm.Text = "";
                        NewPasswd = "";
                    }
                    
                    try
                    {
                       
                            id = Int16.Parse(Session["mid"].ToString());
                            NewPasswd = FormsAuthentication.HashPasswordForStoringInConfigFile(NewPasswd, "MD5");
                            DBaccess db1 = new DBaccess();
                            int read1 = db.ExecSql("update mr_member set password='" + NewPasswd + "' where mid='" + id + "'");
                            //sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["testLottery"].ConnectionString);
                            // sqlcon.Open();
                            // cmd = "update Member set password='" + NewPasswd + "' where uid='" + id + "'";
                            Session["password"] = NewPasswd;
                        
                        //sqlcmd = new SqlCommand(cmd, sqlcon);
                        ErrorReport.BorderWidth = 0;
                        ErrorReport.BackColor = Color.Red;
                        ErrorReport.ForeColor = Color.Black;
                        ErrorReport.Text = "修改成功！";
                        ErrorReport.Visible = true;
                        //sqlcmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqle)
                    {
                        ;
                    }
                    finally
                    {
                       // sqlcon.Close();
                    }
                }
                else
                {
                    ErrorReport.Visible = true;
                    ErrorReport.ForeColor = Color.Red;
                    ErrorReport.BorderWidth = 1;
                    ErrorReport.BackColor = Color.FromArgb(255, 174, 201);
                    ErrorReport.Text = "两次密码不一致，请重新输入！";
                    NewPassword.Text = "";
                    PasswordConfirm.Text = "";
                    OldPassword.Text = "";
                }
            }
            else
            {
                ErrorReport.Visible = true;
                ErrorReport.ForeColor = Color.Red;
                ErrorReport.BorderWidth = 1;
                ErrorReport.BackColor = Color.FromArgb(255, 174, 201);
                ErrorReport.Text = "新密码格式不对，请重新输入！";
                NewPassword.Text = "";
                PasswordConfirm.Text = "";
                OldPassword.Text = "";
            }
        }
        else
        {
            ErrorReport.Visible = true;
            ErrorReport.ForeColor = Color.Red;
            ErrorReport.BorderWidth = 1;
            ErrorReport.BackColor = Color.FromArgb(255, 174, 201);
            ErrorReport.Text = "旧密码错误，请核实！";
            NewPassword.Text = "";
            PasswordConfirm.Text = "";
            OldPassword.Text = "";
        }
    }

    private int RegConfirm(string str)
    {
        String TextRegex = "^[A-Za-z0-9]+$";
        if ((Regex.IsMatch(str, TextRegex)))
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        if ((int)Session["gid"] == 1)
        {
            Response.Redirect("../Teacher/Teacher.aspx");
        }
        else if ((int)Session["gid"] == 2)
        {
            Response.Redirect("../Student/Student.aspx");
        }
        else
        {
            Response.Redirect("../Login.aspx");
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        GridViewDataBind();
    }
    protected void GridViewDataBind()
    {
        string search = TextBox1.Text;
        DBaccess db = new DBaccess();

        DataTable dt = new DataTable();
        DataSet ds1 = new DataSet();
        ArrayList drarr = new ArrayList();
        ArrayList recoarr = new ArrayList();
        //DataSet ds2 = new DataSet();
        String getCid = HttpContext.Current.Request.QueryString["cid"];
        int i;
        DataSet ds = db.GetDataSet("select rid, rname, logo,keyword,score from mr_resource where rname like'%" + search + "%' or cid in (select cid from mr_course where cname like '%" + search + "%') or owner in (select mid from mr_member where mname like '%" + search + "%')");
        dt.Columns.Add("rid");
        dt.Columns.Add("image");
        dt.Columns.Add("rname");
        dt.Columns.Add("keyword");
        dt.Columns.Add("score");
        dt.Columns.Add("information");
        dt.Columns.Add("删除");
        for (i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = ds.Tables[0].Rows[i]["rid"];
            dr[2] = ds.Tables[0].Rows[i]["rname"];
            dr[3] = ds.Tables[0].Rows[i]["keyword"];
            dr[4] = ds.Tables[0].Rows[i]["score"];
            dr[5] = "information";
            dr[1] = ResolveUrl(ds.Tables[0].Rows[i]["logo"].ToString());
            dt.Rows.Add(dr);
        }

        GridView1.DataSource = dt;
        GridView1.AllowPaging = true;
        GridView1.PageSize = 5;
        GridView1.DataBind();
        //GridView1.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
        //GridView1.Attributes.Add("style", "word-break:break-all;word-wrap:break-word");
        GridView1.Columns[1].ItemStyle.Width = 150;
        GridView1.Columns[3].ItemStyle.Width = 200;
        SqlDataReader last_logn_time = db.GetReader("select last_resource_time from mr_member where mid = '" + Session["mid"] + "'");
        if (last_logn_time.Read())
        {
            string lasttime = last_logn_time.GetValue(0).ToString();
            SqlDataReader count = db.GetReader("select count(*) from mr_resource where upload_time >'" + lasttime + "'");
            if (count.Read())
            {
                HyperLink24.Text = "最新资源（" + count.GetValue(0).ToString() + "）";
            }
            else
                HyperLink24.Text = "最新资源（0）";
        }
    }
    public void SetTop(int tag)
    {
        DBaccess db = new DBaccess();
        DataSet ds = new DataSet();
        String tablename = "mr_test";
        String condition = "";
        DateTime currentTime = new DateTime();
        currentTime = DateTime.Now;
        if (tag == 0)
        {
            tablename = "mr_v_downloadcount";
            LabelTitle.Text = "总排行榜";
        }
        else if (tag == 1)
        {
            tablename = "mr_v_downloadcount_month ";
            condition = "where year = '" + currentTime.Year.ToString() + "' and month = '" + (currentTime.Month - 1).ToString() + "'";
            LabelTitle.Text = "月排行榜";
        }
        else if (tag == 2)
        {
            tablename = "mr_v_downloadcount_year ";
            condition = "where year = '" + currentTime.Year.ToString() + "'";
            LabelTitle.Text = "年排行榜";
        }
        ds = db.GetDataSet("select top 5 * from " + tablename + condition + "  order by num desc");
        HyperLinkRank1.Text = ds.Tables[0].Rows[0]["rname"].ToString();
        HyperLinkRank1.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount1.Text = ds.Tables[0].Rows[0]["num"].ToString();
        HyperLinkRank2.Text = ds.Tables[0].Rows[1]["rname"].ToString();
        HyperLinkRank2.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount2.Text = ds.Tables[0].Rows[1]["num"].ToString();
        HyperLinkRank3.Text = ds.Tables[0].Rows[2]["rname"].ToString();
        HyperLinkRank3.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount3.Text = ds.Tables[0].Rows[2]["num"].ToString();
        HyperLinkRank4.Text = ds.Tables[0].Rows[3]["rname"].ToString();
        HyperLinkRank4.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount4.Text = ds.Tables[0].Rows[3]["num"].ToString();
        HyperLinkRank5.Text = ds.Tables[0].Rows[4]["rname"].ToString();
        HyperLinkRank5.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount5.Text = ds.Tables[0].Rows[4]["num"].ToString();
    }
    protected void ButtonMonth_Click(object sender, EventArgs e)
    {
        SetTop(1);
    }
    protected void ButtonYear_Click(object sender, EventArgs e)
    {
        SetTop(2);
    }
    protected void ButtonAll_Click1(object sender, EventArgs e)
    {
        SetTop(0);
    }
}